<?php

	include 'hash.php';

	//was this successful?
	$successful = true;
	
	//get the post variables
	$username = $_POST['username'];
	$password = $_POST['password'];
	$email = $_POST['email'];
	$firstName = $_POST['firstName'];
	$lastName = $_POST['lastName'];
	$birthDay = $_POST['birthDay'];
	$birthMonth = $_POST['birthMonth'];
	$birthYear = $_POST['birthYear'];
	
	//hash and salt the password
	$hashedPassword = hashPassword($password, $birthDay, $birthMonth, $birthYear);
	
	//generate one of the queries
	//$queryLogin = "INSERT into CS275.userlogin (username, password) VALUES ('$username', '$hashedPassword')";
	$queryLogin = sprintf("INSERT into CS275.userlogin (username, password) VALUES ('%s', '$hashedPassword')", mysql_real_escape_string($username));
	
	//establish connection to MySQL
	$link = mysql_connect('localhost', 'root', 'admin');
	if(!$link){
		$successful = false;
		die('Could not connect: ' . mysql_error());	
	}
	
	//do the first query
	$result = mysql_query($queryLogin, $link);
	
	//if it failed
	if (!$result) {
		$successful = false;
    	$message  = 'Invalid query: ' . mysql_error() . "\n";
    	$message .= 'Whole query: ' . $queryLogin;
    	die($message);
	}
	
	//get the row id
	$id = mysql_insert_id();	
	
	//free the result
	mysql_free_result($result);
	
	//make the second query
	//$queryInfo = "INSERT into CS275.userinfo (id, email, firstName, lastName, birthDay, birthMonth, birthYear) VALUES ('$id', '$email', '$firstName', '$lastName', '$birthDay', '$birthMonth', '$birthYear')";
	$queryInfo = sprintf("INSERT into CS275.userinfo (id, email, firstName, lastName, birthDay, birthMonth, birthYear) VALUES ('$id', '%s', '%s', '%s', '%s', '%s', '%s')", mysql_real_escape_string($email),mysql_real_escape_string($firstName), mysql_real_escape_string($lastName), mysql_real_escape_string($birthDay), mysql_real_escape_string($birthMonth), mysql_real_escape_string($birthYear));
	
	//do the query
	$result = mysql_query($queryInfo, $link);
	
	//if it failed
	if (!$result) {
		$successful = false;
    	$message  = 'Invalid query: ' . mysql_error() . "\n";
    	$message .= 'Whole query: ' . $queryInfo;
    	die($message);
	}
	
	//free the result
	mysql_free_result($result);
	
	//close MySQL connection
	mysql_close($link);
	
	//make false print false, true for true
	$boolarray = Array(false => 'false', true => 'true');
	
	//output json
	echo(json_encode(array("successful" => $boolarray[$successful], "id" => $id)));

?>